#include "expdetails.h"
#include "ui_expdetails.h"
#include<QtSql/QSqlQuery>
#include<QDebug>
#include<QDesktopWidget>
#include<QMessageBox>
//This shows details of specific expense record and allow user to delete or update details
ExpDetails::ExpDetails(int id,int flag_page,QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ExpDetails)
{
    ui->setupUi(this);
    QRect in=QApplication::desktop()->availableGeometry(this);
    ui->scrollArea->setGeometry(0,0,(in.width()),(in.height()));
    ui->label_dtl->setFocus();
    flag=flag_page;
    expid=id;
    int fontSize=10;
    ui->label_dtl->setFont(QFont( "lucida", fontSize, QFont::Normal, FALSE ));
    ui->label_acc->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->label_amt->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->label_cat->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->label_date->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->label_note->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->comboBox_acc->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->comboBox_cat->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->dateEdit->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->lineEdit_amt->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->textEdit_note->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->pushButton_delete->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    ui->pushButton_save->setFont(QFont( "lucida", (fontSize-2), QFont::Normal, FALSE ));
    QAction* backAction = new QAction( tr("Back"), this );
     backAction->setSoftKeyRole( QAction::NegativeSoftKey );
     connect(backAction, SIGNAL(triggered()), this, SLOT(back()));
     addAction( backAction );
     ui->lineEdit_amt->setValidator(new QDoubleValidator(this));
     if(db.db_connect())
     {

         QSqlQuery q;
         int accid=0;
         //Select details of specific record
         if(q.exec(QString("select acc_id,cat_name,exp_amt,exp_date,note from expense_table where exp_id=%1").arg(id)))
         {
            q.next();
            amount=q.value(2).toDouble();
            ui->lineEdit_amt->setText(QString("%1").arg(amount));
            dd=q.value(3).toDate();
            ui->dateEdit->setDate(dd);
            ui->textEdit_note->setText(q.value(4).toString());
            namecat=q.value(1).toString();
            qDebug()<<namecat;
            accid=q.value(0).toInt();
            qDebug()<<accid;
        }
         if(namecat.compare("Unknown")==0)
         {
             //Category unknown means its deleted
              ui->comboBox_cat->addItem("Unknown");

         }
           if(accid==0)
         {
               //Account id 0 means this account is deleted
               nameacc="Unknown";
               ui->comboBox_acc->addItem("Unknown");

           }
           else
           {
               if(q.exec(QString("select name from account_table where account_id=%1").arg(accid)))
               {
                   q.next();
                   nameacc=q.value(0).toString();
               }

           }
        qDebug()<<nameacc;
        qDebug()<<namecat;

         if(q.exec(QString("select category_name from category_table")))
         {
             while(q.next())
                ui->comboBox_cat->addItem(q.value(0).toString(),Qt::UserRole);
            int i= ui->comboBox_cat->findText(namecat);
             ui->comboBox_cat->setCurrentIndex(i);
         }
         if(q.exec(QString("select name from account_table")))
         {
             while(q.next())
                ui->comboBox_acc->addItem(q.value(0).toString(),Qt::UserRole);
            int i= ui->comboBox_acc->findText(nameacc);
             ui->comboBox_acc->setCurrentIndex(i);
         }

         db.db_close();
     }
}
void ExpDetails::setMonth(QString m)
{
    month=m;
}

ExpDetails::~ExpDetails()
{
    delete ui;
}
void ExpDetails::setDate(QDate f,QDate t)
{
    from=f;
    to=t;
}
void ExpDetails::go_back()
{
    if(flag==1)//Go to today view
            (new ExpToday)->show();
    else if(flag==2)
        (new ExpMonthView(1,month,dd.month(),dd.year()))->show();
    else if(flag==3)
        (new ExpMonthView(2,month,dd.month(),dd.year()))->show();
    else if(flag==4)//Go to custom view
        (new ExpRange(from,to))->show();
    else if(flag==5)//Go to category view
        (new ExpCatView(1,namecat))->show();
    else if(flag==6)//Go to account view
        (new ExpCatView(2,nameacc))->show();

}

void ExpDetails::back()
{

    go_back();


}

void ExpDetails::on_pushButton_save_clicked()
{
    QString acc=ui->comboBox_acc->currentText();
    QString cat=ui->comboBox_cat->currentText();
    double amt=ui->lineEdit_amt->text().toDouble();
    QDate dt=ui->dateEdit->date();
    QString note=ui->textEdit_note->toPlainText();
    if(db.db_connect())
    {
        QSqlQuery qry;
        if(qry.exec(QString("select account_id,budget_amt,expense_amt from account_table where name='%1'").arg(acc)))
        {
            int id=0;
           if(qry.next())
            {
             id=qry.value(0).toInt();
             double budget=qry.value(1).toDouble();
             double expense=qry.value(2).toDouble();
            QString query;
             if(amount>amt)
            {
                 query=QString("update account_table set account_amt=account_amt+%1,expense_amt=expense_amt-%2 where account_id=%3").arg(amount-amt).arg(amount-amt).arg(id);
                 if(qry.exec(query))
                 {
                     qDebug()<<"Updated amounts";
                 }
             }
             else if(amount<amt)
             {
                 query=QString("update account_table set account_amt=account_amt-%1,expense_amt=expense_amt+%2 where account_id=%3").arg(amt-amount).arg(amt-amount).arg(id);
                 if(qry.exec(query))
                 {
                     qDebug()<<"Updated amounts";
                 }
             }
             //Expense record is updated by changing account and category references

             if(budget!=0)
             {
                 if(expense>budget)
                     QMessageBox::information(0,"Error!",QString("Total amount of expenses exceeds budget assigned to '%1' account").arg(acc));
             }//Alarm generation

         }//If account is not Unknown
            qry.prepare(QString("update expense_table set acc_id=?,cat_name=?,exp_amt=?,note=?,exp_date=? where exp_id=?"));
            qry.addBindValue(id);
            qry.addBindValue(cat);
            qry.addBindValue(amt);
            qry.addBindValue(note);
            qry.addBindValue(dt);
            qry.addBindValue(expid);
           // if(db.db_exp_update(expid,qry.value(0).toInt(),cat,amt,note,dt.toString()))
            if(qry.exec())
                QMessageBox::information(0,"Done !","Updated expense !");
            else
                QMessageBox::warning(0,"Error !","Can not update expense");
        }
        db.db_close();
    }



}

void ExpDetails::on_pushButton_delete_clicked()
{
    QMessageBox msg;
   // msg.setText("It will delete expense permanently");
    msg.setInformativeText("Do you really want to delete ?");
    msg.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
    msg.setDefaultButton(QMessageBox::Yes);
    int res=msg.exec();
    if(res==QMessageBox::Yes)
    {
    if(db.db_connect())
    {
        QSqlQuery qry;
        if(qry.exec(QString("select exp_amt,acc_id from expense_table where exp_id=%1").arg(expid)))
        {
         qry.next();
        int accid=qry.value(1).toInt();
        double amt=qry.value(0).toDouble();
        if(qry.exec(QString("update account_table set account_amt=account_amt+%1,expense_amt=expense_amt-%2 where account_id=%3").arg(amt).arg(amt).arg(accid)))
        {
            qDebug()<<"Updated";
        if(db.db_exp_delete(expid))
        {

            QMessageBox::information(0,"Done !","Deleted expense !");
            go_back();
        }
    }
    }
        else
            QMessageBox::warning(0,"Error !","Can not delete expense");
        db.db_close();
    }
}
}
